package org.weatherapplication;

import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class CitiesListAdapter extends BaseAdapter {
	private Activity context;
	private ArrayList<String> cities;
	private TextView tvCityName;
	
	public CitiesListAdapter(Activity mContext) {
		this.setContext(mContext);
		cities = new ArrayList<String>();
	}
	
	/** Numele orasului este adaugat doar daca nu mai exista in lista. */
	public void addCity(String cityName) {
		if (!cities.contains(cityName)) {
			cities.add(cityName);
			
			//sortare folosind ordinea naturala a String-urilor din cities
			Collections.sort(cities);
			
			this.notifyDataSetChanged();
		}
	}
	
	public boolean removeCity(int position) {
		cities.remove(position);
		notifyDataSetChanged();
		return true;
	}
	
	public int getCount() {
		return cities.size();
	}
	
	public Object getItem(int position) {
		return cities.get(position);
	}
	
	public long getItemId(int position) {
		return 0;
	}
	
	public View getView(int position, View convertView, ViewGroup list) {
		View element;
        if (convertView == null) {
        	LayoutInflater inflater = context.getLayoutInflater();
        	element = inflater.inflate(R.layout.list_item, null);
        }
        else 
        	element = convertView;
        
        tvCityName = (TextView) element.findViewById(R.id.tvCityName);
    	tvCityName.setText(cities.get(position));
    	
        return element;
	}
	
	public Activity getContext() {
		return context;
	}
	
	public void setContext(Activity context) {
		this.context = context;
	}
	
	/** Suprascrierea metodei toString() pentru a usura scrierea in fisierul in care vom memora 
	    numele oraselor. */
	@Override
	public String toString() {
		StringBuffer strBuff = new StringBuffer();
		
		for (String s : cities) {
			strBuff.append(s + "\n");
		}
		
		return strBuff.toString();
	}
}
